<template>
  <div class="finance_box" ref="myElementRef">
    <div ref="searchBox">
      <hc-search :data="serchData" @serch="getSarch($event)" @getadd="getadd($event)" />
    </div>
    <!-- 表格 -->
    <div class="table_box">
      <hc-table :tableData="tableData" :column="state.tableHeader" :offsetHeight="state.offsetHeight" :maxPage="maxPage"
        @pageChange="pageChange" @limitChange="limitChange">
        <template #status="{ row }">
          {{ row.status == 1 ? '启用' : '不启用' }}
        </template>
        <template #operation="scope">
          <el-button size="small" type="text" @click="edit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" link @click="del(scope.row)">删除</el-button>
        </template>
      </hc-table>
    </div>
    <!-- 新增 -->
    <el-dialog align-center v-model="dialogVisible" :title="state.title" width="30%" draggable>
      <div class="from_add">
        <el-form style="width: 90%" label-width="100px" :model="formLabelAlign" ref="formRef" :rules="rules">
          <el-form-item label="角色编码" prop="roleCode">
            <el-input v-model="formLabelAlign.roleCode" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="formLabelAlign.roleName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="formLabelAlign.status" class="m-2" placeholder="请选择">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input class="text_input" v-model="formLabelAlign.description" type="textarea" :rows="4"
              placeholder="请输入" />
          </el-form-item>
          <el-form-item label="权限设置">
            <div style="border: 1px ridge rgb(217 214 214);width: 100%;border-radius: 5px;">
              <el-tree ref="treeRef" style="max-width: 600px" :data="RoleData" show-checkbox node-key="permission_id"
                :props="defaultProps"   @check="handleCheck" />
                
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="subimt($refs.formRef)"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import hcSearch from "@/components/hc-search/index.vue";
import hcTable from "@/components/hc-table/index.vue";
import { onMounted, reactive, ref, nextTick, onUnmounted, onActivated } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { RolesAdd, RolesUpdate, RolesDel, RolesList, RolePermissionsList } from '@/api/system.js';
const treeRef = ref(null);                // 绑定 el-tree 的 ref
const checkedKeys = ref([]);              // 存储选中值
const xuanData = ref([]); 

const myElementRef = ref();
const searchBox = ref();
const dialogVisible = ref(false);
const options = reactive([
  { label: "不启用", value: 0 },
  { label: "启用", value: 1 },
])
let page = ref(1);
let limit = ref(20);
let maxPage = ref(0);
const rules = reactive({
  roleName: [
    {
      required: true,
      message: "角色编号不能为空",
      trigger: "blur",
    },
  ],
  roleCode: [
    {
      required: true,
      message: "角色名称不能为空",
      trigger: "blur",
    },
  ],
});
const formLabelAlign = reactive({
  roleName: "",
  roleCode: "",
  description: "",
  status: 1,
  checkedKeys:[]
});
const tableData = ref([]);

const serchData = reactive([
  {
    label: "角色名称",
    type: "input",
    value: "",
  },

  {
    label: "",
    type: "add",
    value: true
  }

]);

const state = reactive({
  dialogShow: true,
  title: "编辑信息",
  column: [
    {
      type: "index",
      show: true,
      label: "序号",
      width: 80,
    },
    {
      prop: "role_code",
      show: true,
      label: "角色编码",
    },
    {
      prop: "role_name",
      show: true,
      label: "角色名称",
    },
    {
      prop: "description",
      show: true,
      label: "角色描述",
    },
    {
      prop: "status",
      show: true,
      label: "状态",
      width: 140,
    },
    {
      prop: "created_at",
      show: true,
      label: "创建时间",
      width: 160,
    },
    {
      prop: "operation",
      show: true,
      width: 200,
      label: "操作",
    },
  ],
  flng: true,
  offsetHeight: 0,
  tableHeader: [],
});
const RoleData = ref([]);
const defaultProps = {
  children: 'children',
  label: 'permission_name'
}

onMounted(() => {
  try {
    nextTick(() => {
      offHeighths();
    });
    window.onresize = () => {
      nextTick(() => {
        offHeighths();
      });
    };
    tableHeaderFn();
  } catch { }
  getRoleList();
  getList();
});
// 动态改变表头
const change = (item) => {
  tableHeaderFn();
};
const getRoleList = async (id) => {
  const res = await RolePermissionsList({
    role_id: id
  });
  RoleData.value = res.data || [];
};
const handleCheck = () => {
 // 1. 获取当前所有勾选key
 const checked = treeRef.value.getCheckedKeys(true); // true 为叶子+非叶子
  // 2. 构建一个以permission_id为key的所有节点FlatMap
  function buildMap(list, parentId = null, map = {}) {
    list.forEach(node => {
      map[node.permission_id] = {
        ...node,
        parentId,
      }
      if (node.children && node.children.length) {
        buildMap(node.children, node.permission_id, map)
      }
    })
    return map
  }
  const nodesMap = buildMap(RoleData.value);

  // 3. 递归向上找父节点id
  function addParent(id, set) {
    const node = nodesMap[id];
    if (node && node.parentId && !set.has(node.parentId)) {
      set.add(node.parentId);
      addParent(node.parentId, set);
    }
  }
  const result = new Set([...checked]);
  checked.forEach(id => {
    addParent(id, result);
  });

  checkedKeys.value = Array.from(result);
  // console.log('包含所有父节点的已选permission_id:', checkedKeys.value);
  formLabelAlign.checkedKeys=Array.from(result);
  // console.log(formLabelAlign)
};

function applyCheckedKeys(ids = []) {
  nextTick(() => {
    if (treeRef.value) {
      treeRef.value.setCheckedKeys(ids)
    }
  })
}
// 删除
const del = (row) => {
  ElMessageBox.alert('确认要删除角色信息吗', '删除提醒', {
    confirmButtonText: '确认',
    callback: (action) => {
      if (action == "confirm") {
        // console.log(111)
        getDel(row)
      }

    },
  })
};

const getDel = async (row) => {
  // console.log(serchData[0].value)
  const res = await RolesDel({
    roleId: row.role_id
  });
  if (res.code === 200) {
    // dialogVisible.value = false;
    ElMessage.success('删除成功');
  } else {
    ElMessage.error(res.msg || '删除失败');
  }
  getList()
};

// 编辑
const edit = async (row) => {
  // console.log(row)
  Object.assign(formLabelAlign, {
    roleId: row.role_id,
    roleName: row.role_name,
    roleCode: row.role_code,
    description: row.description,
    status: row.status,
  })
  // 如果后端返回该角色已有的权限ID集合，则用于回显
  formLabelAlign.checkedKeys = Array.isArray(row.checkedKeys) ? row.checkedKeys : (formLabelAlign.checkedKeys || [])
  dialogVisible.value = true;
  // 等待弹窗和树渲染后再设置，避免 treeRef 为空
  applyCheckedKeys(formLabelAlign.checkedKeys)
};

const offHeighths = () => {
  if (myElementRef.value) {
    state.offsetHeight =
      myElementRef.value?.offsetHeight - 130 - searchBox.value?.offsetHeight;
  }
};

onUnmounted(() => {
  window.onresize = null;
});

// 查询过来的数据
const getSarch = (data) => {
  // console.log("查询", data);
  page.value = 1
  getList()
};

const getadd = () => {
  // console.log("新增");
  
  
  Object.assign(formLabelAlign, {
    roleName: "",
    roleCode: "",
    description: "",
    status: 1,
    roleId: null,
    checkedKeys:[]
  })
  dialogVisible.value = true
};

// 表头筛选
const tableHeaderFn = () => {
  state.tableHeader = state.column.filter((v) => {
    if (v.show) {
      return v.show == true;
    } else {
      v.show = false;
    }
  });
};


const pageChange = (currentPage) => {
  // console.log(currentPage, "0002")
  page.value = currentPage;
  // getSearch(searchData)
  getList();
}

const limitChange = (currentLimit) => {
  // console.log(currentLimit, "0001")
  page.value = 0;
  limit.value = currentLimit;
  getList();
}

const getList = async () => {
  // console.log(serchData[0].value)
  const res = await RolesList({
    page: page.value,
    limit: limit.value,
    role_name: serchData[0].value
  });
  tableData.value = res.data || [];
  maxPage.value = res?.maxPage || 0;
};

const subimt = async (formEl) => {
  if (!formEl) return;

  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const data = { ...formLabelAlign };
        // console.log(data)
        if (data.roleId > 0) {
          const res = await RolesUpdate(data);
          if (res.code === 200) {
            dialogVisible.value = false;
            ElMessage.success('修改成功');
          } else {
            ElMessage.error(res.msg || '修改失败');
          }
        } else {
          const res = await RolesAdd(data);
          if (res.code === 200) {
            dialogVisible.value = false;
            ElMessage.success('保存成功');
          } else {
            ElMessage.error(res.msg || '保存失败');
          }
        }
        getList()

      } catch (error) {
        ElMessage.error('保存失败，请重试');
      } finally {

      }
    } else {
      ElMessage.warning('请填写完整的信息');
    }
  });
};

</script>

<style lang="less" scoped>
.finance_box {
  flex: 1;
  overflow: auto;
  background-color: #fff;
  border-radius: 6px;
  padding: 10px;
  margin-right: 10px;
}

.btn_box {
  height: 40px;
  display: flex;
}

.table_box {
  width: 100%;
}

/deep/.el-button-group .el-button--primary:first-child {
  background-color: #1e6aed;
  border: none;
}

.serBtn {
  margin-left: 10px;
  background-color: #f0f0f0;
  color: #000;
  border: none;
}

.serBtn:hover {
  background-color: #f0f0f0;
  color: #000;
}

.from_add {
  display: flex;
  width: 100%;
  justify-content: center;
}

.tree_itme {
  min-height: 400px;
}
</style>
